#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>

void *read_mouse(void *arg) {
    printf("正在读取鼠标事件!\n");
    int fd = *(int *)arg;
    unsigned char buffer[8]; // 假设鼠标事件是8字节
    ssize_t bytesRead;

    while (1) {
        bytesRead = read(fd, buffer, sizeof(buffer));
        if (bytesRead == -1) {
            perror("read mouse error");
            exit(1);
        } else if (bytesRead > 0) {
            printf("Mouse event: ");
            for (ssize_t i = 0; i < bytesRead; i++) {
                printf("%02x ", buffer[i]);
            }
            printf("\n");
        }
    }
}

void *read_key(void *arg) {
    sleep(15);
    char buffer[1024];
    while (1) {
        memset(buffer, 0, sizeof(buffer));
        ssize_t bytesRead = read(0, buffer, sizeof(buffer) - 1); // 留一个位置给 '\0'
        if (bytesRead == -1) {
            perror("read key error");
            exit(1);
        } else if (bytesRead > 0) {
            printf("Key input: %s\n", buffer);
        }
    }
}

int main(int argc, char **argv) {
    pthread_t id1;
    pthread_t id2;

    int fd = open("/dev/input/mouse0", O_RDONLY);
    if (fd == -1) {
        perror("open mice error!");
        exit(1);
    }

    int ret = pthread_create(&id1, NULL, read_mouse, (void *)&fd);
    if (ret < 0) {
        perror("thread read mouse error!");
        close(fd);
        exit(1);
    }

    ret = pthread_create(&id2, NULL, read_key, NULL);
    if (ret < 0) {
        perror("thread read key error!");
        close(fd);
        exit(1);
    }

    pause();

    close(fd);
    return 0;
}
